package com.xzlf.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xzlf.domain.TFile;
import com.xzlf.service.JobTaskService;
import com.xzlf.service.MailService;
import com.xzlf.service.TFileService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class TestMailTask implements SchedulingConfigurer {
    @Autowired
    private JobTaskService jobTaskService;
    @Autowired
    private MailService mailService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private TFileService tFileService;

    @Value("${task.lock.key1}")
    private String lockKey1;

    @Value("${task.lock.key2}")
    private String lockKey2;

    @Value("${task.lock.key3}")
    private String lockKey3;

    @Value("${task.lock.value1}")
    private String lockValue1;

    @Value("${task.lock.value2}")
    private String lockValue2;

    @Value("${task.lock.value3}")
    private String lockValue3;

    @Value("${server.name}")
    private String serverName;

    @Value("${job.execute.enable}")
    private boolean isExecute;


    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                () -> {
                   mailService.sendMaill("【邮件】");
                   /**
                    //从RedissonClient取得Rlock实例
                    RLock rLock = redissonClient.getLock(lockKey2);
                    try {
                        //尝试取锁，有效期为3s，到期后自动释放。如果取得锁继续执行。取锁失败则自旋。
                        //使用rlock.tryLock（）方法，此方法也为尝试取锁，并返回boolean结果
                        boolean lock = rLock.tryLock(2, 6, TimeUnit.SECONDS);
                        if (!lock) {
                            return;
                        }

                        log.info("我是：{}，抢到了锁，使用线程：{}，开始执行任务：task_2", serverName, Thread.currentThread().getName());
                        TFile one = tFileService.getOne(new QueryWrapper<TFile>()
                                .select("id", "name")
                                .likeRight("name", "task_2_")
                                .orderByDesc("id").last("limit 1"));
                        String name = one == null ? null : one.getName();
                        if (name == null) {
                            name = "task_2_001";
                        } else {
                            int i = Integer.parseInt(name.substring(name.lastIndexOf('_') + 1));
                            name = "task_2_" + String.format("%03d", (i + 1));
                        }
                        System.out.println("=================" + name);
                        TFile tFile = new TFile(name, "task_2", "create By " + serverName);
                        tFileService.save(tFile);
                        TimeUnit.SECONDS.sleep(4);
                        log.info("我是：{}，完成了任务task_2。", serverName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (rLock.isLocked()) {
                            if (rLock.isHeldByCurrentThread()) {
                                log.info("我是：{}，完成了任务task_2，开始释放锁。", serverName);
                                rLock.unlock();
                            }
                        } else {
                            log.info("我是：{}，没有抢到锁，无需释放。", serverName);
                        }
                    }
                    */
                },
                new Trigger() {
                    @Override
                    public Date nextExecutionTime(TriggerContext triggerContext) {
                        CronTrigger cronTrigger = new CronTrigger(jobTaskService.getById(2).getJobCron());
                        Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);
                        return nextExecutionTime;
                    }
                }
        );
    }
}
